const cart = {
  namespaced: true,
  mutations: {
    // 添加购物车
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('cart/saveTostorage')
    },
    // 持久化存储
    saveTostorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 更新数据
    updateGoodsState(state, good) {
      const fr = state.cart.find(x => x.goods_id === good.goods_id)
      if (fr && good.type === 1) {
        fr.goods_state = good.goods_state
      } else {
        fr.goods_count = good.goods_count
      }
      this.commit('cart/saveTostorage')
    },
    // 全部选中
    selectAll(state) {
      if (state.cart.every(y => y.goods_state === true)) {
        state.cart.forEach(z => z.goods_state = false)
      } else {
        state.cart.forEach(x => {
          x.goods_state = true
        })
      }
      this.commit('cart/saveTostorage')
    },
    // 删除商品
    deleteItem(state, good) {
      state.cart = state.cart.filter(x => x.goods_id !== good)
      this.commit('cart/saveTostorage')
    }
  },
  state: {
    cart: JSON.parse(uni.getStorageSync('cart') || "[]")
  },
  getters: {
    // 统计数量
    count(state) {
      return state.cart.reduce((total, item) => total += item.goods_count, 0)
    },
    // 控制全选勾选状态
    allselect(state) {
      return state.cart.every(x => x.goods_state === true)
    },
    // 统计选中商品
    selected(state) {
      // const list = state.cart.filter(x => x.goods_state === true)
      return state.cart.filter(x => x.goods_state === true)
    }
  }
}

export default cart
